package com.yangcangclub.mq.domain;

import com.google.common.collect.Maps;
import com.yangcangclub.commons.exception.ApolloException;
import com.yangcangclub.commons.result.MessageEnum;
import com.yangcangclub.mq.base.MQBaseDomain;
import com.yangcangclub.mq.bean.MQConsumeLogInfo;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class MQLogProfile extends MQBaseDomain {

    /**
     * 获取offset
     * @param consumer
     * @param partition
     * @param topic
     * @param tag
     * @return
     */
    public int addMQLog(String consumer,int partition,String topic, String tag,int message_id,int state){
        MQConsumeLogInfo mqConsumeLogInfo = new MQConsumeLogInfo();
        mqConsumeLogInfo.setConsumer(consumer);
        mqConsumeLogInfo.setPartition_(partition);
        mqConsumeLogInfo.setTopic(topic);
        mqConsumeLogInfo.setTag(tag);
        mqConsumeLogInfo.setMessage_id(message_id);
        mqConsumeLogInfo.setState(state);

        int num = super.getSlaveJdbc().selectOne("mq.MQMapper.selectConsumerConsumerLogCount",mqConsumeLogInfo);
        if(num>0) {
            return 0;
        }

        super.getMasterJdbc().insert("mq.MQMapper.insertConsumerLog", mqConsumeLogInfo);

        if(mqConsumeLogInfo.getId()==0) {
            //回滚
            throw new ApolloException(MessageEnum.DATABASE_ERROR);
        }

        return mqConsumeLogInfo.getId();
    }

    /**
     * 更新state
     * @param id
     * @param state
     * @return
     */
    public boolean updateMqLog(int id,int state) {

        Map<String,Object> map = Maps.newHashMap();
        map.put("id", id);
        map.put("state", state);

        int i =  super.getMasterJdbc().update("mq.MQMapper.updateConsumerLog", map);

        if(i != 1) {
            //回滚
            throw new ApolloException(MessageEnum.DATABASE_ERROR);
        }

        return true;
    }

}
